/**
 * NPC数据初始化脚本
 * 功能：创建NPC基础表并初始化基础NPC数据
 */

const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

// 数据库配置
const DB_CONFIG = {
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs'
};

// 基础NPC集群数据
const INITIAL_NPC_CLUSTER_DATA = [
    // 新手村 (areaId: 2)
    {
        id: 9003,
        name: "陌生美女",
        typeId: 2,
        areaId: 2,
        attackPower: 0,
        details: [
            {
                name: "陌生美女",
                description: "一位神秘的美丽女子，似乎有什么话要对你说。",
                image: "meinv",
                level: 1,
                count: 1,
                attackPower: 0,
                defense: 0,
                health: 100,
                expReward: 0,
                silverReward: 0,
                dropItems: null
            }
        ]
    },
    {
        id: 106,
        name: "打手群",
        typeId: 1,
        areaId: 2,
        attackPower: 15,
        details: [
            {
                name: "打手",
                description: "一群凶恶的打手，专门欺负弱小。",
                image: "dashou",
                level: 5,
                count: 3,
                attackPower: 15,
                defense: 8,
                health: 80,
                expReward: 50,
                silverReward: 20,
                dropItems: JSON.stringify([{ id: 1001, name: "铜钱", rate: 0.3 }])
            }
        ]
    },
    {
        id: 125,
        name: "黄巾军群",
        typeId: 1,
        areaId: 2,
        attackPower: 20,
        details: [
            {
                name: "黄巾军",
                description: "黄巾起义军的残部，虽然装备简陋但人数众多。",
                image: "huangjin",
                level: 8,
                count: 5,
                attackPower: 20,
                defense: 12,
                health: 120,
                expReward: 80,
                silverReward: 35,
                dropItems: JSON.stringify([{ id: 1002, name: "布衣", rate: 0.2 }])
            }
        ]
    },
    {
        id: 1990,
        name: "流氓群",
        typeId: 1,
        areaId: 2,
        attackPower: 12,
        details: [
            {
                name: "流氓",
                description: "一群无赖流氓，经常在街头闹事。",
                image: "liumang",
                level: 3,
                count: 2,
                attackPower: 12,
                defense: 6,
                health: 60,
                expReward: 30,
                silverReward: 15,
                dropItems: JSON.stringify([{ id: 1003, name: "破布", rate: 0.4 }])
            }
        ]
    },

    // 成都 (areaId: 70)
    {
        id: 118,
        name: "逃兵群",
        typeId: 1,
        areaId: 70,
        attackPower: 25,
        details: [
            {
                name: "逃兵",
                description: "从战场上逃回来的士兵，虽然疲惫但仍有战斗力。",
                image: "taobing",
                level: 12,
                count: 4,
                attackPower: 25,
                defense: 15,
                health: 150,
                expReward: 120,
                silverReward: 50,
                dropItems: JSON.stringify([{ id: 1004, name: "军刀", rate: 0.15 }])
            }
        ]
    },
    {
        id: 205,
        name: "山贼群",
        typeId: 1,
        areaId: 70,
        attackPower: 30,
        details: [
            {
                name: "山贼",
                description: "盘踞在山中的盗匪，专门抢劫过往商旅。",
                image: "shanzei",
                level: 15,
                count: 6,
                attackPower: 30,
                defense: 18,
                health: 180,
                expReward: 150,
                silverReward: 70,
                dropItems: JSON.stringify([{ id: 1005, name: "山贼刀", rate: 0.1 }])
            }
        ]
    },

    // 九里山 (areaId: 487)
    {
        id: 1396,
        name: "士兵群",
        typeId: 1,
        areaId: 487,
        attackPower: 40,
        details: [
            {
                name: "士兵",
                description: "训练有素的士兵，装备精良。",
                image: "shibing",
                level: 20,
                count: 8,
                attackPower: 40,
                defense: 25,
                health: 250,
                expReward: 200,
                silverReward: 100,
                dropItems: JSON.stringify([{ id: 1006, name: "铁剑", rate: 0.08 }])
            }
        ]
    },
    {
        id: 1591,
        name: "强盗群",
        typeId: 1,
        areaId: 487,
        attackPower: 50,
        details: [
            {
                name: "强盗",
                description: "拦路抢劫的恶棍！恶贯满盈！",
                image: "qiangdao",
                level: 25,
                count: 10,
                attackPower: 50,
                defense: 30,
                health: 300,
                expReward: 250,
                silverReward: 120,
                dropItems: JSON.stringify([{ id: 1007, name: "强盗刀", rate: 0.05 }])
            }
        ]
    }
];

async function initNpcData() {
    let connection;

    try {
        console.log('🚀 开始初始化NPC数据...\n');

        // 1. 连接数据库
        console.log('1️⃣ 连接数据库...');
        connection = await mysql.createConnection(DB_CONFIG);
        console.log('✅ 数据库连接成功');

        // 2. 创建NPC表
        console.log('\n2️⃣ 创建NPC表...');
        await createNpcTables(connection);
        console.log('✅ NPC表创建成功');

        // 3. 初始化NPC数据
        console.log('\n3️⃣ 初始化NPC数据...');
        await insertNpcData(connection);
        console.log('✅ NPC数据初始化完成');

        // 4. 验证数据
        console.log('\n4️⃣ 验证数据...');
        await verifyNpcData(connection);

        console.log('\n🎉 NPC数据初始化完成！');

    } catch (error) {
        console.error('❌ 初始化失败:', error.message);
        throw error;
    } finally {
        if (connection) {
            await connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }
}

async function createNpcTables(connection) {
    // 创建NPC集群表
    const createClusterTableSQL = `
    CREATE TABLE IF NOT EXISTS npc_clusters (
      id INT PRIMARY KEY COMMENT 'NPC集群ID',
      name VARCHAR(100) NOT NULL COMMENT '集群名称',
      areaId INT NOT NULL COMMENT '所属区域ID',
      typeId INT NOT NULL COMMENT '集群类型ID (1:怪物群, 2:NPC)',
      attackPower INT DEFAULT 0 COMMENT '攻击力',
      isActive TINYINT DEFAULT 1 COMMENT '是否激活 (1:激活, 0:禁用)',
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
      updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
      INDEX idx_area_id (areaId),
      INDEX idx_type_id (typeId),
      INDEX idx_is_active (isActive)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='NPC集群表';
  `;

    // 创建NPC详情表
    const createDetailTableSQL = `
    CREATE TABLE IF NOT EXISTS npc_details (
      id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'NPC详情ID',
      clusterId INT NOT NULL COMMENT '所属集群ID',
      name VARCHAR(100) NOT NULL COMMENT 'NPC名称',
      description VARCHAR(200) NOT NULL COMMENT 'NPC描述',
      image VARCHAR(100) NOT NULL COMMENT 'NPC图片',
      level INT NOT NULL COMMENT 'NPC等级',
      count INT NOT NULL COMMENT 'NPC数量',
      attackPower INT DEFAULT 0 COMMENT '攻击力',
      defense INT DEFAULT 0 COMMENT '防御力',
      health INT DEFAULT 100 COMMENT '生命值',
      expReward INT DEFAULT 0 COMMENT '经验值奖励',
      silverReward INT DEFAULT 0 COMMENT '银两奖励',
      dropItems VARCHAR(500) NULL COMMENT '掉落物品列表(JSON格式)',
      isActive TINYINT DEFAULT 1 COMMENT '是否激活 (1:激活, 0:禁用)',
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
      updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
      INDEX idx_cluster_id (clusterId),
      INDEX idx_is_active (isActive),
      FOREIGN KEY (clusterId) REFERENCES npc_clusters(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='NPC详情表';
  `;

    await connection.execute(createClusterTableSQL);
    await connection.execute(createDetailTableSQL);
}

async function insertNpcData(connection) {
    for (const clusterData of INITIAL_NPC_CLUSTER_DATA) {
        try {
            // 检查集群是否已存在
            const [existingCluster] = await connection.execute(
                'SELECT id FROM npc_clusters WHERE id = ?',
                [clusterData.id]
            );

            if (existingCluster.length > 0) {
                console.log(`⏭️ NPC集群已存在: ${clusterData.name} (ID: ${clusterData.id})`);
                continue;
            }

            // 插入集群数据
            const insertClusterSQL = `
        INSERT INTO npc_clusters (
          id, name, areaId, typeId, attackPower, isActive
        ) VALUES (?, ?, ?, ?, ?, ?)
      `;

            await connection.execute(insertClusterSQL, [
                clusterData.id, clusterData.name, clusterData.areaId,
                clusterData.typeId, clusterData.attackPower, 1
            ]);

            console.log(`✅ 创建NPC集群: ${clusterData.name} (ID: ${clusterData.id}, 区域: ${clusterData.areaId})`);

            // 插入集群下的NPC详情
            if (clusterData.details && clusterData.details.length > 0) {
                for (const detailData of clusterData.details) {
                    const insertDetailSQL = `
            INSERT INTO npc_details (
              clusterId, name, description, image, level, count,
              attackPower, defense, health, expReward, silverReward, dropItems, isActive
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
          `;

                    await connection.execute(insertDetailSQL, [
                        clusterData.id, detailData.name, detailData.description, detailData.image,
                        detailData.level, detailData.count, detailData.attackPower, detailData.defense,
                        detailData.health, detailData.expReward, detailData.silverReward, detailData.dropItems, 1
                    ]);

                    console.log(`  ✅ 创建NPC详情: ${detailData.name} (集群ID: ${clusterData.id})`);
                }
            }

        } catch (error) {
            console.error(`❌ 创建NPC集群 ${clusterData.name} 失败:`, error.message);
        }
    }
}

async function verifyNpcData(connection) {
    try {
        // 统计集群数量
        const [clusterCount] = await connection.execute(
            'SELECT COUNT(*) as count FROM npc_clusters WHERE isActive = 1'
        );
        console.log(`📊 总NPC集群数量: ${clusterCount[0].count}`);

        // 统计详情数量
        const [detailCount] = await connection.execute(
            'SELECT COUNT(*) as count FROM npc_details WHERE isActive = 1'
        );
        console.log(`📊 总NPC详情数量: ${detailCount[0].count}`);

        // 按区域统计集群
        const [areaStats] = await connection.execute(`
      SELECT areaId, COUNT(*) as count 
      FROM npc_clusters 
      WHERE isActive = 1 
      GROUP BY areaId 
      ORDER BY areaId
    `);

        console.log('\n📋 各区域NPC集群统计:');
        for (const stat of areaStats) {
            console.log(`   区域 ${stat.areaId}: ${stat.count} 个集群`);
        }

        // 按类型统计集群
        const [typeStats] = await connection.execute(`
      SELECT typeId, COUNT(*) as count 
      FROM npc_clusters 
      WHERE isActive = 1 
      GROUP BY typeId 
      ORDER BY typeId
    `);

        console.log('\n📋 各类型NPC集群统计:');
        for (const stat of typeStats) {
            const typeName = stat.typeId === 1 ? '怪物群' : 'NPC';
            console.log(`   ${typeName} (${stat.typeId}): ${stat.count} 个`);
        }

    } catch (error) {
        console.error('❌ 验证数据失败:', error.message);
    }
}

// 运行初始化
if (require.main === module) {
    initNpcData().catch((error) => {
        console.error('💥 初始化脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = { initNpcData, INITIAL_NPC_CLUSTER_DATA };
